package hello;


import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;

import video.MIDPPixelSource;
import video.VideoListener;
import connections.BTSerialConnection;

public class HelloVideoBTSender extends MIDlet {



	public VideoCanvas myCanvas;

	public MIDPPixelSource ps;
	
	BTSerialConnection myBTSerial ;

	public void startApp() throws MIDletStateChangeException {

		myCanvas = new VideoCanvas();
		ps = new MIDPPixelSource(160, 120,null,myCanvas);
		Display display = Display.getDisplay(this);
		display.setCurrent(myCanvas);
		// ps = new MIDPPixelSource(160, 120,"http://java.sun.com/products/java-media/mma/media/test-mpeg.mpg", myCanvas);
		// ps = new MIDPPixelSource(160, 120,"http://itp.nyu.edu/~dbo3/cellphone/testvid/h.MPG");
	

		myBTSerial = new BTSerialConnection(null, "00A096179A85");
	
	}

	public void pauseApp() {
	}

	public void destroyApp(boolean arg0) throws MIDletStateChangeException {
		System.out.println("destroy");
	}

	public class VideoCanvas extends Canvas  {

		int x;

		int y;

		Image myImage;

		String feedback = "";

		public void keyPressed(int keyCode) {
			System.out.println(keyCode);

			System.out.println("Keycode" + keyCode);

			if (keyCode == Canvas.KEY_NUM4) {
				x--;
			} else if (keyCode == Canvas.KEY_NUM6) {
				x++;
			} else if (keyCode == Canvas.KEY_NUM5) {
				// grab 
				ps.grabFrame();
				byte[] imageBytes = ps.getCompressedImageBytes();
				String extraInfo = "Picture" + ","  + String.valueOf(System.currentTimeMillis()) + ".png"; // use a timestamp for the filename on the server
				//send it
				//FilePoster myPost = new FilePoster(imageBytes, "http://itp.nyu.edu/~dbo3/up.php", extraInfo);
				myBTSerial.send(imageBytes, extraInfo);
							
			}

		}

	

		public void put(String _s) {
			System.out.println(_s);
			String feedback = _s;
		}

		public void paint(Graphics g) {
			if(ps.requiresManualPainting()){
				ps.grabFrame();
				myImage = ps.getImage();
				if (myImage != null) {
					g.setColor(255);
					g.fillRect(0, 0, getWidth(), getHeight());
					g.drawImage(myImage, x, y, 0);
					g.setColor(0);
					g.drawString(feedback, x, y, 0);
				}
			}
		}

	}
}
